#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "SoundManager.h"

SoundManager::SoundManager() : device(NULL), background(NULL)
{
	foregroundSounds.clear();
}

SoundManager::~SoundManager()
{
	if(background)
		background->release();
	device = NULL;
}

bool SoundManager::initialize()
{
	device = audiere::OpenDevice();
	if(!device)
		return false;
	device->registerCallback(this);
	return true;
}

float SoundManager::getBackgroundVolume()
{
	return backgroundVolume;
}

void SoundManager::setBackgroundVolume(float volume)
{
	backgroundVolume = volume;
	if(background)
		background->getAudiereSound()->setVolume(backgroundVolume / 100.0f);
}

float SoundManager::getForegroundVolume()
{
	return foregroundVolume;
}

void SoundManager::setForegroundVolume(float volume)
{
	foregroundVolume = volume;

	std::list<Sound*>::iterator it;
	for(it = foregroundSounds.begin(); it != foregroundSounds.end(); it++)
		(*it)->getAudiereSound()->setVolume(foregroundVolume / 100.0f);
}

void SoundManager::stopAll()
{
	stopBackground();

	while(foregroundSounds.size() != 0)
		stopForeground(*(foregroundSounds.begin()));
}
void SoundManager::pauseAll()
{
	pauseBackground();

	std::list<Sound*>::iterator it;
	for(it = foregroundSounds.begin(); it != foregroundSounds.end(); it++)
		pauseForeground(*it);
}
void SoundManager::stopBackground()
{
	if(background)
	{
		background->getAudiereSound()->stop();
		background->getAudiereSound()->reset();
		background = NULL;
	}
}
void SoundManager::pauseBackground()
{
	if(background)
	{
		background->getAudiereSound()->stop();
	}
}
void SoundManager::stopForeground(Sound* sound)
{
	sound->getAudiereSound()->stop();
	sound->getAudiereSound()->reset();
	foregroundSounds.remove(sound);
}
void SoundManager::pauseForeground(Sound* sound)
{
	sound->getAudiereSound()->stop();
}
void SoundManager::playBackground(Sound* sound)
{
	stopBackground();
	background = sound;

	setBackgroundVolume(backgroundVolume);
	background->getAudiereSound()->setRepeat(true);
	background->getAudiereSound()->play();

}
void SoundManager::playForeground(Sound* sound)
{
	sound->getAudiereSound()->play();
	foregroundSounds.push_back(sound);
}

void ADR_CALL SoundManager::streamStopped(audiere::StopEvent* event)
{
	if(audiere::StopEvent::STREAM_ENDED != event->getReason())
		return;

	std::list<Sound*>::iterator it;
	for(it = foregroundSounds.begin(); it != foregroundSounds.end(); it++)
	{
		if((*it)->getAudiereSound() == event->getOutputStream())
		{			
			foregroundSounds.remove(*it);
			return;
		}
	}
}
